﻿using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Configuration;
using System.IO;

public class FileServerAuthHeader : SoapHeader
{
    public string Username;
    public string Password;
}

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class FileServer : System.Web.Services.WebService
{
    public FileServerAuthHeader Authentication;
    private string WebServerPath;

    /// <summary>
    /// Constructor
    /// </summary>
    public FileServer()
    {
        WebServerPath = ConfigurationSettings.AppSettings["WebServerRootPath"];
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private bool CheckAuthen()
    {
        //return true;
        return (Authentication.Username == "violympicservice" && Authentication.Password == "violympic12345%$#@!");
    }
    /// <summary>
    /// 
    /// </summary>
    public enum FileExtensions{htm, html, asp, aspx, jpg, gif, dll, exe, all };
    
    /// <summary>
    /// Kiem tra su ton tai cua thu muc
    /// </summary>
    /// <param name="Path"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public bool DirectoryExists(string Path)
    {
        if (!CheckAuthen()) return false;
        DirectoryInfo dir = new DirectoryInfo(WebServerPath + Path);
        return dir.Exists;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Path"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public string GetAllSubDirectory(string Path)
    {
        if (!CheckAuthen()) return null;
        string result="";
        try
        {
            DirectoryInfo subdirs = new DirectoryInfo(WebServerPath + Path);
            DirectoryInfo[] dirs = subdirs.GetDirectories();
            foreach (DirectoryInfo directory in dirs)
            {
                if (result == "")
                {
                    result = directory.Name;
                }
                else
                {
                    result += "|" + directory.Name;
                }
            }
        }
        catch 
        {
            return "";
        }
        
        return result;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Path"></param>
    /// <param name="FileName"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public bool FileExists(string Path, string FileName)
    {
        if (!CheckAuthen()) return false;
        DirectoryInfo dir;
        try
        {
            dir = new DirectoryInfo(WebServerPath + Path);
            if (!dir.Exists)
            {
                return false;
            }
            FileInfo[] aFile = dir.GetFiles();
            foreach(FileInfo file in aFile)
            {
                if (file.Name == FileName)
                {
                    return true;
                    break;
                }
            }
        }
        catch 
        {
            return false;
        }
        return false;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="VirtualPath"></param>
    /// <param name="FileExtension"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public FileInformation[] Browse(string VirtualPath, FileExtensions FileExtension)
    {
        if (!CheckAuthen()) return null;
        int i=0;
        FileInformation[] aFiles;
        string mExtension;

        switch (FileExtension)
        { 
            case FileExtensions.asp:
                mExtension = "asp";
                break;
            case FileExtensions.aspx:
                mExtension = "aspx";
                break;
            case FileExtensions.gif:
                mExtension = "gif";
                break;
            case FileExtensions.htm:
                mExtension = "htm";
                break;
            case FileExtensions.html:
                mExtension = "html";
                break;
            case FileExtensions.jpg:
                mExtension = "jpg";
                break;
            case FileExtensions.dll:
                mExtension = "dll";
                break;
            case FileExtensions.exe:
                mExtension = "exe";
                break;
            case FileExtensions.all:
                mExtension = "*";
                break;
            default:
                mExtension = "violympic";
                break;
        }
        DirectoryInfo dir = new DirectoryInfo(WebServerPath + VirtualPath);
        FileInfo[] afi = dir.GetFiles("*." + mExtension);
        aFiles = new FileInformation[afi.Length - 1];
        foreach (FileInfo file in afi)
        { 
            aFiles[i] = new FileInformation();
            aFiles[i].Name = file.Name;
            aFiles[i].Size = file.Length;
            aFiles[i].LastAccess = file.LastAccessTime;
            aFiles[i].CreadedDate = file.CreationTime;
            aFiles[i].LastModified = file.LastWriteTime;
            aFiles[i].FileType = file.Extension;
            aFiles[i].FileLocation = file.DirectoryName;
            aFiles[i].FileContent = ReadFile(WebServerPath + VirtualPath + "\\" + file.Name);
            i += 1;
        }
        return aFiles;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="FilePath"></param>
    /// <returns></returns>
    public byte[] ReadFile(string FilePath)
    {
        FileStream fs = null;
        try
        {
            fs = File.Open(FilePath, FileMode.Open, FileAccess.Read);
            long lngLen = fs.Length;
            int LenOfArray = Convert.ToInt32(lngLen);
            byte[] abytBuffer = new byte[LenOfArray];
            fs.Read(abytBuffer, 0, Convert.ToInt32(lngLen));
            return abytBuffer;
        }
        catch (Exception ex)
        {
            return null;
        }
        finally {
            fs.Close();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="VirtualPath"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public string GetAllFileNameInDirectory(string VirtualPath)
    {
        if (!CheckAuthen()) return null;

        string ListOfFileName = "";
        try
        {
            foreach(string FileName in Directory.GetFiles(WebServerPath + VirtualPath, "*.*"))
            {
                if(ListOfFileName=="")
                    ListOfFileName = System.IO.Path.GetFileName(FileName);
                else
                    ListOfFileName = ListOfFileName + "|" + System.IO.Path.GetFileName(FileName);
            }
        }
        catch
        {
            return "";
        }
        return ListOfFileName;
    }
    /// <summary>
    /// Lay file
    /// </summary>
    /// <param name="VirtualPath">Duong dan den thu muc chua file</param>
    /// <param name="FileName">Ten file</param>
    /// <returns>Moi mang byte chua noi dung file</returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public byte[] GetFile(string VirtualPath, string FileName)
    {
        if (!CheckAuthen()) return null;

        return ReadFile(WebServerPath + VirtualPath + "\\" + FileName);
    }
    /// <summary>
    /// Upload moi file len server
    /// </summary>
    /// <param name="VirtualPath">Duong dan den thu muc</param>
    /// <param name="Name">Ten file</param>
    /// <param name="Content">Noi dung file(moi mang byte du lieu)</param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public string UploadFile(string VirtualPath, string Name, byte[] Content)
    {
        if (!CheckAuthen()) return null;

        FileStream objFstream = null;
        try
        {
            if(!System.IO.Directory.Exists(WebServerPath + VirtualPath))
            {
                System.IO.Directory.CreateDirectory(WebServerPath + VirtualPath);
            }
        }
        catch
        {
            return "Create directory error!";
        }
        try
        {
            objFstream = File.Open(WebServerPath + VirtualPath + "\\" + Name, FileMode.Create, FileAccess.Write);
            long lngLen = Content.Length;
            objFstream.Write(Content, 0, Convert.ToInt32(lngLen));
            objFstream.Flush();
            objFstream.Close();
            return "File uploaded!";
        }
        catch(System.UnauthorizedAccessException exc)
        {
            return exc.ToString();
        }
        catch(Exception exc)
        {
            return exc.ToString();
        }
        finally{
            objFstream.Close();
        }
    }
    /// <summary>
    /// Xoa file
    /// </summary>
    /// <param name="Filepath">Duong dan den thu muc chua file</param>
    /// <returns>True: Xoa thanh cong, False: Khong ton tai file</returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public bool File_Delete(string Filepath)
    {
        if (!CheckAuthen()) return false;

        FileInfo fi = new FileInfo(WebServerPath + Filepath);

        if (fi.Exists)
        {
            fi.Delete();
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="FilepathOld"></param>
    /// <param name="FilepathNew"></param>
    /// <returns></returns>
    //[SoapHeader("Authentication", Required = true)]
    //[WebMethod]
    //public bool File_rename( string Path, string FileOldName, string FileNewName)
    //{
    //    if (!CheckAuthen()) return null;
    //
    //    FileInfo fi = new FileInfo(WebServerPath + Path + FileOldName);
    //    if (fi.Exists)
    //    {
    //        fi.MoveTo(WebServerPath + Path + FileNewName);
    //        return true;
    //    }
    //    else
    //    {
    //        return false;
    //    }
    //}
    /// <summary>
    /// Doi ten file
    /// </summary>
    /// <param name="Path">Duong dan den thu muc chua file</param>
    /// <param name="FileOldName">Ten file cu</param>
    /// <param name="FileNewName">Ten file moi</param>
    /// <param name="OverWrite">Ghi de len file co ten cung voi ten file moi</param>
    /// <returns>True: Doi ten thanh cong, False: Khong doi duoc ten file</returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public bool File_rename(string Path, string FileOldName, string FileNewName, bool OverWrite)
    {
        if (!CheckAuthen()) return false;

        FileInfo fi  = new FileInfo(WebServerPath + Path + FileOldName);
        FileInfo fi2 = new FileInfo(WebServerPath + Path + FileNewName);
        if (fi.Exists)
        {
            if (fi2.Exists && OverWrite)
            {
                fi2.Delete();
            }
            else if (fi2.Exists)
            {
                return false;
            }

            fi.MoveTo(WebServerPath + Path + FileNewName);
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="OldPath"></param>
    /// <param name="NewPath"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public bool Folder_rename(string OldPath, string NewPath)
    {
        if (!CheckAuthen()) return false;

        try
        {
            Directory.Move(OldPath, NewPath);
        }
        catch 
        {
            return false;
        }
        return true;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Path"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public bool Folder_delete(string Path)
    {
        if (!CheckAuthen()) return false;

        try
        {
            Directory.Delete(Path,true);
        }
        catch
        {
            return false;
        }
        return true;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Path"></param>
    /// <returns></returns>
    [SoapHeader("Authentication", Required = true)]
    [WebMethod]
    public DateTime GetDateTime()
    {
        return DateTime.Now;
    }
}
public class FileInformation
{
    public string Name;
    public long Size;
    public DateTime CreadedDate;
    public DateTime LastModified;
    public DateTime LastAccess;
    public string FileType;
    public string FileLocation;
    public byte[] FileContent;
}
